/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package connexionOracle;

import java.io.IOException;
import java.security.*;
import javax.crypto.*;
import org.apache.commons.codec.binary.Base64;
import javax.crypto.spec.SecretKeySpec;

/**
 *
 * @author Administrateur
 */
public class Crypt {
private Key key = null;
private byte[] keyBytes = "B@6b97fd".getBytes();

    /**
     * Generates the encryption key. using "des" algorithm
     *
     * @throws NoSuchAlgorithmException
     */
    public void generateKey() throws NoSuchAlgorithmException {
    key = new SecretKeySpec(keyBytes, "DES");
    }

    public String encrypt(String message) throws Exception {
	// Get a cipher object.
	Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
	cipher.init(Cipher.ENCRYPT_MODE, key);

	// Gets the raw bytes to encrypt, UTF8 is needed for
	// having a standard character set
	byte[] stringBytes = message.getBytes("UTF8");

	// encrypt using the cypher
	byte[] raw = cipher.doFinal(stringBytes);

	// converts to base64 for easier display.
	Base64 encoder = new Base64();
	String base64 = encoder.encode(raw).toString();

	return base64;
    }

     public String decrypt(String encrypted) throws InvalidKeyException,
	    NoSuchAlgorithmException, NoSuchPaddingException,
	    IllegalBlockSizeException, BadPaddingException, IOException {

		// Get a cipher object.
		Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
		cipher.init(Cipher.DECRYPT_MODE, key);

		//decode the BASE64 coded message
		Base64 decoder = new Base64();
		byte[] raw = decoder.decode(encrypted);

		//decode the message
		byte[] stringBytes = cipher.doFinal(raw);

		//converts the decoded message to a String
		String clear = new String(stringBytes, "UTF8");
		return clear;
    }

    /**
     *
     * @param args
     */

    }

